package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bean.Role;
import com.example.bean.User;
import com.example.service.RoleService;
import com.example.until.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @title: RoleController
 * @Author wjf
 * @Date: 2022/9/26 17:04
 * @Version 1.0
 */
@RestController
@CrossOrigin
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping("/page")
    public Result getPage(
            @RequestParam Integer current,
            @RequestParam Integer pageSize,
            @RequestParam String name){
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name),"name",name)
                .orderByDesc("id");
        IPage<Role> page = new Page<>(current,pageSize);
        IPage<Role> page1 = roleService.page(page, queryWrapper);
        return Result.ok(page1);
    }

    @GetMapping("/{id}")
    public Result<Role> getUserById(@PathVariable("id") Integer id){
        Role role = roleService.getById(id);
        return Result.ok(role);
    }

    @GetMapping
    public Result getRole(){
        List<Role> list = roleService.list(null);
        return Result.ok(list);
    }

    @PostMapping("/save")
    public Result<Boolean> saveUser(@RequestBody() Role role) {
        boolean save = roleService.save(role);
        return Result.ok(save);
    }

    @PutMapping("/update")
    public Result<Boolean> putUser(@RequestBody Role role) {
        boolean b = roleService.updateById(role);
        return Result.ok(b);
    }

    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteUser(@PathVariable Integer id) {
        boolean b = roleService.removeById(id);
        return Result.ok(b);
    }

    @DeleteMapping("/delete/batch/{ids}")
    public Result<Boolean> deleteMoreUser(@PathVariable List<Integer> ids){
        boolean b = roleService.removeByIds(ids);
        return Result.ok(b);
    }

    @PostMapping("/roleMenu/{roleId}")
    public Result roleMenu(@PathVariable Integer roleId,@RequestBody List<Integer> menuIds){
        roleService.updateRoleMenu(roleId,menuIds);
      return Result.ok();
    }

    @GetMapping("/roleMenu/{roleId}")
    public Result getRoleMenu(@PathVariable Integer roleId){
       List<Integer> list = roleService.getMenu(roleId);
       return Result.ok(list);
    }

}
